import { useEventEmitter } from 'ahooks';
import { EventEmitter } from 'ahooks/lib/useEventEmitter';
import { ReactNode, useCallback, useEffect, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import { createContext } from 'use-context-selector';

import { DatasetListItem, GetGroupTreeList } from '@/common';
import { useDatasetStore } from '@/store/datasetStore';
import { TreeData, DatasetEvent } from '@/types/dataset';

type DatasetsContextType = {
  fetchDatasets: () => void;
  allDatasets: DatasetListItem[];
  loading: boolean;
  // dataset: DatasetListItem | null;
  selectedTreeData: TreeData[];
  selectedTreeNode: TreeData | undefined;
  fullTreeData: TreeData[];
  selectedTreeKeys: string[];
  checkedTreeDatas: TreeData[];
  currentDataset: TreeData | undefined;
  currentEditTreeData: TreeData | undefined;
  event$: EventEmitter<DatasetEvent> | null;
  setLoading: (loading: boolean) => void;
  setSelectedTreeData: (data: TreeData[]) => void;
  // getDatasetDetail: () => void;
  setSelectedTreeNode: (node: TreeData | undefined) => void;
  setFullTreeData: (data: TreeData[]) => void;
  setSelectedTreeKeys: (keys: string[]) => void;
  setCurrentDataset: (data: TreeData | undefined) => void;
  setCurrentEditTreeData: (data: TreeData | undefined) => void;
  setCheckedTreeDatas: (data: TreeData[]) => void;

  isDelete: boolean;
  setIsDelete: (isDelete: boolean) => void;

  updateExpiredTime: TreeData | undefined;
  setUpdateExpiredTime: (node: TreeData) => void;

  isHighlight: boolean;
  setIsHighlight: (isHighlight: boolean) => void;

  users: GetGroupTreeList[];
  setUsers: (users: GetGroupTreeList[]) => void;
};

export const DatasetsContext = createContext<DatasetsContextType>({
  fetchDatasets: () => {},
  allDatasets: [],
  loading: false,
  // dataset: null,
  selectedTreeData: [],
  selectedTreeNode: undefined,
  fullTreeData: [],
  selectedTreeKeys: [],
  event$: null,
  currentDataset: undefined,
  currentEditTreeData: undefined,
  checkedTreeDatas: [],
  setLoading: () => {},
  setSelectedTreeData: () => {},
  // getDatasetDetail: () => {},
  setSelectedTreeNode: () => {},
  setFullTreeData: () => {},
  setSelectedTreeKeys: () => {},
  setCurrentDataset: () => {},
  setCurrentEditTreeData: () => {},
  setCheckedTreeDatas: () => {},

  isDelete: false,
  setIsDelete: () => {},

  updateExpiredTime: undefined,
  setUpdateExpiredTime: () => {},

  isHighlight: false,
  setIsHighlight: () => {},

  users: [],
  setUsers: () => {},
});

const DatasetsContextProvider = ({ children }: { children: ReactNode }) => {
  const { allDatasets, loadAllDatasets } = useDatasetStore();
  const [selectedTreeData, setSelectedTreeData] = useState<TreeData[]>([]);
  const [selectedTreeNode, setSelectedTreeNode] = useState<TreeData | undefined>(undefined);
  const [fullTreeData, setFullTreeData] = useState<TreeData[]>([]);
  const [selectedTreeKeys, setSelectedTreeKeys] = useState<string[]>([]);
  const [currentDataset, setCurrentDataset] = useState<TreeData | undefined>();
  const [currentEditTreeData, setCurrentEditTreeData] = useState<TreeData | undefined>();
  const [checkedTreeDatas, setCheckedTreeDatas] = useState<TreeData[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const event$ = useEventEmitter<DatasetEvent>();
  const [updateExpiredTime, setUpdateExpiredTime] = useState<TreeData>();
  const [isDelete, setIsDelete] = useState<boolean>(false);
  const [isHighlight, setIsHighlight] = useState<boolean>(false);
  const [users, setUsers] = useState<GetGroupTreeList[]>([]);
  // const [dataset, setDataset] = useState<DatasetListItem | null>(null);
  const [searchParams] = useSearchParams();
  const id = searchParams.get('id');
  const fetchDatasets = useCallback(() => {
    try {
      setLoading(true);
      loadAllDatasets({
        parentId: null,
        page: 1,
        page_size: 10,
        user_id: '67fcd7c1de9ddb56bea37b6c', // 这个id需要从浏览器的url地址上面获取
        offset: 0,
        searchText: '',
        groupId: '',
      });
      console.log('来了context里面');
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    const flag = checkedTreeDatas.every((item) => item?.experiodDays !== null);
    setIsHighlight(flag);
  }, [checkedTreeDatas]);

  // const getDatasetDetail = useCallback(async ()=>{
  //   const dataset = await datasetService.getDatasetDetail(id)
  //   return dataset
  // }, [id])

  // const { data: data, run: fetchDatasetDetail, } = useRequest(getDatasetDetail, {
  //   cacheKey: id + "cache-dataset-detail",
  //   retryCount: 3,
  //   refreshDeps: [id]
  // });

  const contextValue: DatasetsContextType = {
    fetchDatasets,
    allDatasets,
    // dataset: data ?? null,
    selectedTreeData,
    loading,
    selectedTreeNode,
    fullTreeData,
    selectedTreeKeys,
    currentDataset,
    currentEditTreeData,
    event$,
    checkedTreeDatas,
    setLoading,
    setSelectedTreeData,
    // getDatasetDetail: fetchDatasetDetail,
    setSelectedTreeNode,
    setFullTreeData,
    setSelectedTreeKeys,
    setCurrentDataset,
    setCurrentEditTreeData,
    setCheckedTreeDatas,
    isDelete,
    setIsDelete,
    updateExpiredTime,
    setUpdateExpiredTime,
    isHighlight,
    setIsHighlight,
    users,
    setUsers,
  };

  return <DatasetsContext.Provider value={contextValue}>{children}</DatasetsContext.Provider>;
};

export default DatasetsContextProvider;
